package com.shihan.rabbitmq.demo.controller;

import com.rabbitmq.client.ConnectionFactory;
import com.shihan.rabbitmq.demo.config.RabbitMQConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

/**
 * @Description
 * @Author shihan
 * @Date 2021/1/9 22:54
 * @Version 1.0
 */
@RestController
public class BizController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 通过 rest 接口，设置延迟消息
     *
     * @param num
     * @return
     */
    @RequestMapping("/delay/seconds/{num}")
    public String delayMessage(@PathVariable("num") Integer num) throws UnsupportedEncodingException {
        // 通过消息属性设置，消息的延迟时间为 num 秒！
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("x-delay", num * 1000);

        // 创建要发送的消息，并且指定上述配置的消息属性
        Message message = new Message(("延迟消费的消息，设定为 " + num + " 秒之后进行消费！").getBytes("utf-8"), messageProperties);

        // 将消息发送到 延迟交换器中
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_DELAYED, RabbitMQConfig.BINDING_KEY_DELAYED, message);

        return "定时消息设置成功，将于 " + num + " 秒后进行消费！";
    }

    /**
     * 发送普通消息
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/common/msg")
    public String commonMessage() throws UnsupportedEncodingException {
        // 创建一个 MessageProperties 对象，并需要赋值给 Message，否则会报错
        MessageProperties messageProperties = MessagePropertiesBuilder.newInstance().build();

        // 创建要发送的消息
        Message message = new Message("普通消息".getBytes("utf-8"), messageProperties);

        // 将消息发送到 普通交换器中
        rabbitTemplate.send(RabbitMQConfig.EXCHANGE_NAME_COMM, RabbitMQConfig.BINDING_KEY_COMM, message);

        return "普通消息发送成功！";
    }

}
